/** 
 
*/
import React, { PureComponent } from 'react';
import { PrimaryC, FirstHeaderC, SecondHeaderC, PrimaryGhostC, TableC } from '../../../../comps';
import { Row, Col, message, Modal } from 'antd';
import style from './index.less';
import HoldInfoC from './holdInfoC';
import StandardTradeC from './standardTradeC';
import BaseInfoC from './baseInfoC';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';
import { uniqueKey } from '../../../../utils/commonFunc';

class AddBuyBackOrderC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      portfolioId: undefined, //组合id
      infoAvaliable: {}, //标准券可用张数
      holdInfo: undefined, //持仓表格的数据
      isShow: false,
      query: {},
      trailColumns: [], //试算结果列表
      trailDataSource: [], //试算结果数据
      trailModel: false, //试算模态框
      productCode: undefined, //产品code
      portfolioCode: undefined, //组合code
      uid: '',
    };
  }
  componentDidMount() {
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  //指令下达 簿记保存 获取form表单数据并校验
  confirmClick = () => {
    const {
      user: { currentUser },
      dispatch,
      type,
    } = this.props;
    const { infoAvaliable, holdInfo } = this.state;
    if (!this.baseInfo.state.isCanOrder && type == 1) {
      //在点击“下达”时，若标记指示未配置指令，则提示用户“该组合为配置指令，无法下发指令。
      message.warning(this.props.errorSetMsg);
      return;
    }
    this.baseInfo.formGroupThis.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        //获取委托方向
        if (type == 10) {
          this.orderSave(values);
          return;
        } else if ('1' == values.trade7.orderSide) {
          //融券 判断有没有钱 (交易所回购现券根据t+1可用)
          this.orderSave(values);
        } else if ('2' == values.trade7.orderSide) {
          //融资 判断有没有标准券可用
          if (values.trade7.orderuseQty && values.trade7.tradingmarket) {
            //委托数量
            //101 上交所 105 深交所
            let bzky = 0;
            if ('101' === values.trade7.tradingmarket) {
              bzky = infoAvaliable[0] || 0;
            } else {
              bzky = infoAvaliable[1] || 0;
            }
            if (bzky < values.trade7.orderuseQty) {
              message.error('标准券不足');
              return;
            } else {
              this.orderSave(values);
            }
          }
        }

        if ('3' == values.trade7.orderSide) {
          //提交质押 判断单个债券的 可用数量
          dispatch({
            type: 'exchangePledgeM/queryAvailableAmount',
            payload: {
              portfolioId: values.trade7.portfolioId,
              tradingcode: values.trade7.tradingcode,
            },
            callback: (data) => {
              if (data !== undefined) {
                if (data < values.trade7.orderuseQty) {
                  message.error('可用数量不足');
                } else {
                  this.orderSave(values);
                }
              }
            },
          });
        } else if ('4' == values.trade7.orderSide) {
          //转回质押 与左边表格的质押数量对比
          const msg = '质押数量不足';
          if (!holdInfo) {
            return message.error(msg);
          }
          const temp = holdInfo.filter((item) => {
            return item.tradingcode == values.trade7.tradingcode;
          });
          if (temp.length) {
            if (temp[0].pledgeAmount < values.trade7.orderuseQty) {
              message.error(msg);
            } else {
              this.orderSave(values);
            }
          } else {
            message.error(msg);
          }
        }
      }
    });
  };

  //指令下达 簿记保存请求后台
  orderSave = (params) => {
    const {
      user: { currentUser },
      dispatch,
      type,
    } = this.props;
    if (type != 10) params.trade7.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
    params.trade7.userNumber = currentUser.userId;
    params.portfolioId = type == 10 ? params.listId : params.trade7.portfolioId;
    //创建日期
    params.trade7.creationDate = moment().format('YYYYMMDD');
    params.type = 7;
    params.userId = currentUser.userId;
    params.userName = currentUser.name;
    params.uid = this.state.uid;
    if (type == 2) {
      params.method = '0';
    }
    if (type == 10) {
      params.method = null;
      dispatch({
        type: 'exchangePledgeM/tradeBookSave',
        payload: {
          ...params,
        },
        callback: (data) => {
          if (data) {
            message.success('交易录入成功!');
            this.props.onOk();
            this.baseInfo.getTradingCodeList('1', '101');
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
      return;
    }

    if (type == 1) {
      //指令
      if (this.state.isShow) {
        dispatch({
          type: 'exchangePledgeM/saveOrder',
          payload: {
            ...params,
          },
          callback: (data) => {
            if (data) {
              message.success('指令下达成功!');
              this.setState({ isShow: false }, () => {
                this.baseInfo.formGroupThis.props.form.resetFields();
                this.baseInfo.setState({
                  isCanOrder: true,
                  isRequired: true,
                });
                this.baseInfo.getTradingCodeList('1', '101');
                this.portfolioOnChange(undefined); //组合id清空 并抛出
              });
            }
            const uid = uniqueKey();
            uid.then((r) => {
              this.setState({ uid: r });
            });
          },
        });
      } else {
        params.productId = params.trade7.portfolioId; //这个是沿用老接口 产品组合字段是反的 回填时注意
        params.portfolioInfoId = params.trade7.productId;
        this.setState({ isShow: true, query: params });
      }
    } else if (type == 2) {
      //簿记
      dispatch({
        type: 'exchangePledgeM/saveOrderTradeBook',
        payload: {
          ...params,
        },
        callback: (data) => {
          if (data) {
            message.success('簿记下达成功!');
            this.props.onOk();
            this.baseInfo.formGroupThis.props.form.resetFields();
            this.baseInfo.setState({
              isCanOrder: true,
              isRequired: true,
            });
            this.baseInfo.getTradingCodeList('1', '101');
            this.portfolioOnChange(undefined); //组合id清空 并抛出
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else {
      //组合试算
      dispatch({
        type: 'portfolioTrialAddM/exchangePledgSave',
        payload: {
          ...params,
        },
        callback: (data) => {
          if (data) {
            message.success('组合试算下达成功!');
            this.baseInfo.getTradingCodeList('1', '101');
            this.props.onOk();
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    }
  };
  //点击取消 重置
  cancelClick = () => {
    const { type } = this.props;
    if (type == 2 || type == 10 || type == 11) {
      this.props.onCancel();
    }
    this.baseInfo.formGroupThis.props.form.resetFields();
    this.portfolioOnChange(undefined); //组合id清空 并抛出
    this.baseInfo.setState({
      isCanOrder: true,
      isRequired: true,
    });
    this.baseInfo.getTradingCodeList('1', '101');
  };
  //组合id变更事件
  portfolioOnChange = (e) => {
    this.setState({
      portfolioId: e,
    });
    this.props.portfolioIdChange(e); //抛出组合id
  };
  // 系列产品
  seriesProductsOnChange = (e) => {};

  // 二次确认点击取消
  handleCancel = () => {
    this.setState({
      isShow: false,
      query: {},
    });
  };

  // 二次确认model框
  showModel = () => {
    const { query, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认下达',
      width: 1100,
    };
    return (
      <div style={{ marginLeft: '200px' }}>
        <Modal {...modalProps} onOk={this.confirmClick} onCancel={this.handleCancel} confirmLoading={loading.effects['exchangePledgeM/saveOrder'] === true}>
          <BaseInfoC type={'3'} info={query} />
        </Modal>
      </div>
    );
  };

  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };

  //基本信息
  showInfo = () => {
    const { loading, type, listId } = this.props;
    let url = type == 1 ? 'exchangePledgeM/saveOrder' : type == 11 ? 'portfolioTrialAddM/exchangePledgSave' : 'exchangePledgeM/saveOrderTradeBook';
    return (
      <>
        <div style={{ marginTop: '20px' }}>
          <SecondHeaderC title={'基本信息'} />
          <BaseInfoC
            type={type}
            listId={listId}
            portfolioOnChange={(e) => {
              this.portfolioOnChange(e);
            }}
            seriesProductsOnChange={(e) => {
              this.seriesProductsOnChange(e);
            }}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            onRef={(ref) => {
              this.baseInfo = ref;
            }}
          />
        </div>
        <div className={'btnOperate1'}>
          {/* {type == "2" && <PrimaryC
            loading={loading.effects['trailM/trialData'] === true}
            onClick={() => this.trialOnClick()}
            title={'试算'}
            style={{ marginRight: "10px" }}
          />} */}
          <PrimaryC title={this.props.type == 1 ? '下达' : '确定'} loading={loading.effects[url] == true} onClick={this.confirmClick} />
          <PrimaryGhostC title={'取消'} onClick={this.cancelClick} style={{ marginLeft: '10px' }} />
        </div>
      </>
    );
  };
  //试算按钮点击
  trialOnClick = () => {
    const {
      type,
      dispatch,
      user: { currentUser },
    } = this.props;
    this.baseInfo.formGroupThis.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.trade7.userNumber = currentUser.userId;
        values.portfolioId = type == 10 ? values.listId : values.trade7.portfolioId;
        //创建日期
        values.trade7.creationDate = moment().format('YYYYMMDD');
        values.type = 7;
        values.userId = currentUser.userId;
        values.userName = currentUser.name;
        values.productCode = this.state.productCode; //产品code
        values.portfolioCode = this.state.portfolioCode; //组合code
        values.tenant = currentUser.tenant; //租户code
        values.businessType = '7';
        if (type == 2) {
          values.method = '0';
        }
        this.setState({ trailModel: true }, () => {
          dispatch({
            type: 'trailM/trialData',
            payload: values,
            callback: (res) => {
              if (res) {
                this.setState({
                  trailColumns: res.columns,
                  trailDataSource: res.dataSource,
                });
              } else {
                this.setState({
                  trailColumns: [],
                  trailDataSource: [],
                });
              }
            },
          });
        });
      }
    });
  };

  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <Modal
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </Modal>
    );
  };
  render() {
    const { portfolioId, isShow, trailModel } = this.state;
    return (
      <div className={style.addOrder}>
        {this.props.type != 10 ? (
          <>
            <FirstHeaderC title={'持仓信息'} />
            <HoldInfoC portfolioId={portfolioId} getData={(e) => this.setState({ holdInfo: e })} />
            <FirstHeaderC title={'交易要素'} topHeight={'10px'} />
            <div style={{ marginTop: '10px' }}>
              <SecondHeaderC title={'标准券信息'} />
            </div>
            <StandardTradeC
              portfolioId={portfolioId}
              getInfoAvaliable={(e) => {
                this.setState({ infoAvaliable: e });
              }}
            />
            {this.showInfo()}
          </>
        ) : (
          <>{this.showInfo()}</>
        )}
        <div>
          {isShow ? <div>{this.showModel()}</div> : null}
          {trailModel && this.showTrail()}
        </div>
      </div>
    );
  }
}
export default connect(({ exchangePledgeM, userM: user, portfolioTrialAddM, loading, trailM, isAccountConfiguredM }) => ({
  exchangePledgeM,
  user,
  portfolioTrialAddM,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
}))(AddBuyBackOrderC);
